package p.ithorns.tools.translator.apt.creator;

import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;
import p.ithorns.tools.translator.apt.BaseProcessor;

/**
 * SetterCreator
 *
 * @author HtL
 * @date 2025/4/3 15:05
 * @since 1.0.0
 */
public class SetterCreator extends BaseMethodCreator {

    public SetterCreator(BaseProcessor processor) throws Exception {
        super(processor);
    }

    public JCMethodDecl create(JCVariableDecl jcVariable) {
        //添加返回值类型
        JCExpression returnType = treeMaker.Type(new Type.JCVoidType());

        //修改方法级别
        JCModifiers modifiers = treeMaker.Modifiers(Flags.PUBLIC);

        //添加方法名称
        Name variableName = jcVariable.getName();
        Name methodName = makeCamelSignature(variableName, "set");

        //设置方法体
        ListBuffer<JCStatement> jcStatements = new ListBuffer<>();
        jcStatements.append(treeMaker.Exec(treeMaker
                .Assign(treeMaker.Select(treeMaker.Ident(getNameFromString("this")), variableName),
                        treeMaker.Ident(variableName))));
        //定义方法体
        JCBlock jcBlock = treeMaker.Block(0, jcStatements.toList());

        List<JCTypeParameter> typeParameters = List.nil();

        //定义参数
        JCVariableDecl variableDecl = treeMaker
                .VarDef(treeMaker.Modifiers(Flags.PARAMETER, List.nil()), jcVariable.name, jcVariable.vartype, null);
        List<JCVariableDecl> parameters = List.of(variableDecl);

        //声明异常
        List<JCExpression> throwsClauses = List.nil();
        JCMethodDecl setter = treeMaker.MethodDef(
                modifiers, methodName, returnType, typeParameters, parameters, throwsClauses, jcBlock, null);
        processor.info("[SetterCreator]-> create Setter for field <{}>: ↲\r\n{}", variableName, setter.toString());
        return setter;
    }

}